package com.ejiaoyi.api.util;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.ejiaoyi.api.dto.Rest;
import com.ejiaoyi.api.dto.RestObject;
import com.ejiaoyi.api.enums.ApiCode;
import com.ejiaoyi.common.exception.CustomException;

/**
 * API 操作相关工具类
 *
 * @author unknownChivalrous
 * @since 2020-03-18
 */
public class ApiUtil {

    public static final long API_REDIS_TIMEOUT = 5*60 * 60;

    /**
     * 数据空值检测
     *
     * @param json             需要检测的JSON数据
     * @param validNotEmptyArr 不能为空的字段名称数组
     */
    public static void validNotEmpty(JSONObject json, String... validNotEmptyArr) throws CustomException {
        for (String columnName : validNotEmptyArr) {
            Object obj = json.get(columnName);
            if (obj == null) {
                Rest rest = new Rest();
                rest.setCode(ApiCode.DATA_REQUIRED);
                rest.setMsg(columnName + " can not be empty!");
                throw new CustomException(JSONObject.toJSONString(rest));
            }
        }
    }

    /**
     * 检测字符串长度
     *
     * @param columnName 字段名称
     * @param str        字符串
     * @param length     长度
     */
    public static void validColumnLength(String columnName, String str, int length) throws CustomException {
        Assert.notEmpty(columnName, "param columnName can not be empty");
        Assert.notEmpty(str, "param str can not be empty");
        Assert.notNull(length, "param length can not be null");

        if (str.length() != length) {
            Rest rest = new Rest();
            rest.setCode(ApiCode.DATA_LENGTH);
            rest.setMsg("the " + columnName + " is not support : " + str + ", the length should be " + length);
            throw new CustomException(JSONObject.toJSONString(rest));
        }
    }

    /**
     * 将json字符串解析为Rest
     *
     * @param json json字符串
     * @return Rest
     */
    public static Rest convertRest(String json) {
        JSONObject jsonObject = JSONObject.parseObject(json);

        Rest rest = new Rest();
        rest.setCode(ApiCode.getEnum(jsonObject.getString("code")));
        rest.setMsg(jsonObject.getString("msg"));
        return rest;
    }

    /**
     * 将json字符串解析为RestObject
     *
     * @param json json字符串
     * @return Rest
     */
    public static RestObject convertRestObject(String json) {
        JSONObject jsonObject = JSONObject.parseObject(json);

        RestObject rest = new RestObject();
        rest.setCode(ApiCode.getEnum(jsonObject.getString("code")));
        rest.setMsg(jsonObject.getString("msg"));
        return rest;
    }
}
